<?php

namespace Home\Controller;

use Lib\Taobaoip;

class ShopOrderController extends CommonController
{

    //商品确定
    public function order_confirm()
    {
        $member_data = session('member_data');

        $address_model = D('Address');
        $member_id = $member_data['accountId'];


        $where = array(
            'member_id' => $member_id,
            'default_address' => '1',
        );

        $address_data = $address_model->getAddressInfo($where);

        $goods_id = I('goods_id');

        $goods_model = D('Goods');

        $goods_w = array(
            'goods_id' => $goods_id,
            'status' => '1',
        );

        $finds = 'goods_id,name,image,price,market_price';

        $goods_data = $goods_model->goodsInfo($goods_w, $finds);
        $goods_data['address_data'] = $address_data;

        json_data(array('data_list' => $goods_data));
    }

    //提交订单
    public function add_order()
    {
        //session 用户信息
        $member_data = session('member_data');
        $member_id = $member_data['accountId'];
        $member_name = $member_data['realName'];
        $member_mobile = $member_data['mobile'];

        //查询商品信息
        $goods_id = I('goods_id');
        $quantity = I('quantity');
        /*$quantity = 1;
        $goods_id = 9;*/

        $goods_model = D('Goods');

        $goods_w = array(
            'goods_id' => $goods_id,
            'status' => '1',
        );


        $goods_data = $goods_model->goodsInfo($goods_w);

        if ($goods_data['status'] == '0') {
            json_error('该商品已停用');
        }

        //查询收货地址
        $address_id = I('address_id');
        //$address_id = 1;

        $address_model = D('Address');

        $address_w = array(
            'member_id' => $member_id,
            'address_id' => $address_id,
        );

        $address_data = $address_model->getAddressInfo($address_w);


        $data['goods_id'] = $goods_id;
        $data['quantity'] = $quantity;
        $data['member_id'] = $member_id;
        $data['name'] = $member_name;
        $data['telephone'] = $member_mobile;

        $data['shipping_name'] = $address_data['name'];
        $data['shipping_address'] = $address_data['address'];
        $data['shipping_tel'] = $address_data['telephone'];

        $data['shipping_province_id'] = $address_data['province_id'];
        $data['shipping_city_id'] = $address_data['city_id'];
        $data['shipping_country_id'] = $address_data['country_id'];
        $data['address_id'] = $address_id;
        $data['date_added'] = time();
        $data['order_num_alias'] = build_order_no();

        $payment_method = I('payment_method');
        //$payment_method = 'installments';

        if ($payment_method == 'installments') {
            $data['order_status_id'] = '0';
        } else {
            $data['order_status_id'] = '-2';
        }

        $data['ip'] = get_client_ip();
        $tip = new Taobaoip();
        $ip_region = $tip->getLocation($data['ip']);
        $data['ip_region'] = $ip_region['region'] . '-' . $ip_region['city'];
        $data['total'] = $goods_data['price'];
        $data['price'] = $goods_data['price'];
        $data['payment_code'] = $payment_method;
        $datas = I('datas');
        //$datas = 12;
        $also_num = monthly_payment($goods_data['price'], $goods_data['after_discount'], $datas);
        $data['also_num'] = $also_num;
        $data['datas'] = $datas;

        //规格
        $goods_option = I('goods_option');

        /*$goods_option = array(
            '0' => array(
                "goods_option_id" => 82,
                "goods_option_value_id" => 221,
                "option_id" => 8,
                "option_value_id" => 26,
                "name" => "内存",
                "value" => "128G",
                "type" => "checkbox",
            ),
            '1' => array(
                "goods_option_id" => 83,
                "goods_option_value_id" => 223,
                "option_id" => 9,
                "option_value_id" => 31,
                "name" => "颜色",
                "value" => "亮黑色",
                "type" => "checkbox",
            ),
        );*/


        $ApiOrder = D('ApiOrder');
        $oid = $ApiOrder->addOrder($data, $goods_data, $goods_option);
        //$oid = true;
        if ($oid) {
            //$url=$this->pay_api(session('payment_method'), $order);
            //跳转到聚合支付页面
            //$order_num_alias = base64_encode($data['order_num_alias']);
            $order_num_alias = $data['order_num_alias'];

            if ($payment_method == 'installments') {

                //添加还款计划

                for ($i = 1; $i <= $datas; $i++) {
                    $staging_d = array(
                        'issue' => $i,
                        'goods_name' => $goods_data['name'],
                        'order_num' => $data['order_num_alias'],
                        'member_id' => $member_id,
                        'member_name' => $member_name,
                        'staging_num' => $datas,
                        'also_num' => $also_num,
                        'not_num' => $also_num,
                        'due_num' => monthly_interest($goods_data['price'], $goods_data['after_discount'], $datas),
                    );

                    if ($i == '1') {
                        $staging_d['still_num'] = $also_num * $datas;
                        session('still_num', $staging_d['still_num']);
                    } else {
                        $still_num = session('still_num');
                        $staging_d['still_num'] = $still_num - $also_num;
                        session('still_num', $staging_d['still_num']);
                    }
                    $staging = M('staging')->add($staging_d);
                }


                $oh['order_id'] = $oid;
                $oh['order_status_id'] = $data['order_status_id'];
                $oh['date_added'] = time();
                $oh_id = M('OrderHistory')->add($oh);

                storage_user_action($member_id, $member_name, C('FRONTEND_USER'), '下了订单 ' . $data['order_num_alias'] . ' 未支付');
                /*$url = C('WEB_URL') . '/order.html';
                echo "<script>alert('订单提交成功，我们正加快审核。');parent.location.href='$url'; </script>";
                die();*/
                json_data('订单提交成功，我们正加快审核。');
            } else {
                //$url = C('WEB_URL') . '/Index/Hj/order_num_alias/' . $order_num_alias;

                //ajax 返回调用支付页
                $re = array(
                    'order_num_alias' => $order_num_alias,
                    'total' => $data['total'],
                );
                json_data($re);
                die();
            }

        } else {
            json_error('提交订单失败');
        }
    }

    //订单列表
    public function order_list()
    {
        //session 用户信息
        $member_data = session('member_data');
        $member_id = $member_data['accountId'];
        $order_status_id = I('order_status_id');
        $where = array(
            'member_id' => $member_id,
        );

        $order_model = D('ApiOrder');

        //状态
        if (!empty($order_status_id)) {
            $where['order_status_id'] = $order_status_id;
        }

        //总数、分页
        $count = $order_model->orderCount($where);

        //接收post转换get
        $_GET['page'] = $_POST['page'];

        //分页数
        $page = $_POST['page'];

        //一页显示的条数
        $num = 10;

        //返回是否有下页数据
        $load = api_page($page, $num, $count);
        $finds = 'order_id,goods_id,price,quantity,express_id,order_num_alias,order_status_id,date_added';
        $order = 'date_added desc';
        $order_list = $order_model->getOrderList($where, $finds, $order, '', $page, $num);

        if (!empty($order_list)) {

            //查询商品信息
            $goods_model = D('Goods');
            //商品ig
            $goods_id = array();
            $order_id = array();
            foreach ($order_list as $k => $v) {
                $goods_id[] = $v['goods_id'];
                $order_id[] = $v['order_id'];
            }

            $goods_id = array_unique($goods_id);

            $finds = 'goods_id,name,image';
            $g_where = array(
                'goods_id' => array('in', $goods_id)
            );

            //查询商品
            $goods_list = $goods_model->goodsList($g_where, $finds, '', '10');

            //查询商品的订单商品规格
            $orderOption_model = D('OrderOption');
            $orderOptio_w = array(
                'order_id' => array('in', $order_id)
            );

            $orderOption_data = $orderOption_model->orderOptioList($orderOptio_w);
            if (!empty($orderOption_data)) {
                $option_data = array();
                foreach ($orderOption_data as $k => $v) {
                    $option_list = M()->query('select * from ' . C('DB_PREFIX') . 'order_goods where order_goods_id=' . $v['order_goods_id'] . ' and order_id=' . $v['order_id']);
                    $option_data[] = $option_list[0];
                }
            }

            //组装商品选项规格
            foreach ($option_data as $k => $v) {
                foreach ($orderOption_data as $kk => $vv) {

                    if ($v['order_goods_id'] == $vv['order_goods_id'] && $v['order_id'] == $vv['order_id']) {
                        $option_data[$k]['option_data'][] = $vv['name'] . ' : ' . $vv['value'];
                    }

                }

            }

            //组装商品信息
            foreach ($order_list as $k => $v) {

                foreach ($goods_list as $kk => $vv) {
                    if ($v['goods_id'] == $vv['goods_id']) {
                        $order_list[$k]['name'] = $vv['name'];
                        $order_list[$k]['image'] = $vv['image'];
                    }
                }
                $order_list[$k]['order_status_text'] = order_stute_text($v['order_status_id']);
                $order_list[$k]['date_added'] = date('Y-m-d H:i:s', $v['date_added']);
            }

            //组装商品选项规格
            foreach ($order_list as $k => $v) {
                foreach ($option_data as $kk => $vv) {
                    if ($v['goods_id'] == $vv['goods_id']) {
                        $order_list[$k]['option_data'] = $vv['option_data'];
                    }
                }

            }

        } else {
            $order_list = array();
        }
        json_data(array('load' => $load, 'data_list' => $order_list));
    }


    //取消、确认收货、删除订单
    public function operate_order()
    {
        //session 用户信息
        $member_data = session('member_data');
        $member_id = $member_data['accountId'];
        $order_id = I('order_id');
        //$order_id = 130;
        $state = I('state');
        //$state = 1;
        $cancel_explain = I('cancel_explain');
        //$cancel_explain = '我不要了哇';

        $where = array(
            'member_id' => $member_id,
            'order_id' => $order_id,
        );


        $order_model = D('ApiOrder');
        $finds = 'goods_id,quantity';
        //查询订单数据
        $order_data = $order_model->getOrderInfo($where, $finds);

        if (empty($order_data)) {
            json_error('订单不存在');
        }

        if ($state == '1') {
            //取消订单
            $update = array(
                'order_status_id' => '-1',
                'cancel_explain' => $cancel_explain,
            );
            $re = $order_model->editOrder($where, $update);

            if ($re) {
                M()->execute("UPDATE " . C('DB_PREFIX') . "goods SET quantity = (quantity + " . (int)$order_data['quantity'] . ") WHERE goods_id = '" . $order_data['goods_id'] . "' AND subtract = '1'");
                json_data('取消成功');
            } else {
                json_error('取消失败');
            }
        } elseif ($state == '3') {

            //确认收货
            $update = array(
                'order_status_id' => '6',
            );
            $re = $order_model->editOrder($where, $update);
            if ($re) {
                json_data('确认成功');
            } else {
                json_error('确认失败');
            }

        } else {
            //删除订单
            $re = $order_model->delOrder($where);
            if ($re) {
                json_data('删除成功');
            } else {
                json_error('删除失败');
            }
        }

    }


    //订单详情
    public function order_details()
    {
        //session 用户信息
        $member_data = session('member_data');
        $member_id = $member_data['accountId'];
        $order_id = I('order_id');
        //$order_id = 130;

        if (empty($order_id)) {
            json_error('参数错误');
        }

        $order_model = D('ApiOrder');
        $where = array(
            'member_id' => $member_id,
            'order_id' => $order_id,
        );

        //查询订单
        $finds = 'order_id,goods_id,price,quantity,express_id,code,order_num_alias,order_status_id,total,date_added,address_id,cancel_explain,also_num,datas,payment_code';
        $order_data = $order_model->getOrderInfo($where, $finds);

        if (!empty($order_data)) {

            //订单下单时间
            $order_data['date_added'] = date('Y-m-d H:i:s', $order_data['date_added']);
            //订单状态
            $order_data['order_status_text'] = order_stute_text($order_data['order_status_id']);

            //查询物流信息
            if ($order_data['order_status_id'] == '5' || $order_data['order_status_id'] == '6') {
                $erxpress['code'] = $order_data['code'];
                $erxpress['express_id'] = $order_data['express_id'];
                $erxpress_data = getExpress($erxpress);

                if (empty($erxpress_data['data'][0])) {
                    $order_data['erxpress_data'] = '：( 该单号暂无物流进展，请稍后再试，或检查公司和单号是否有误。';
                } else {
                    $order_data['erxpress_data'] = array(
                        'erxpress_time' => $erxpress_data['data'][0]['time'],
                        'erxpress_context' => $erxpress_data['data'][0]['context'],
                    );
                }
            } else {
                if (empty($order_data['cancel_explain'])) {
                    $o_tetx = '系统取消';
                    $yy = '原因： 超过24小时未付款，系统自动取消';
                } else {
                    $o_tetx = '用户主动取消';
                    $yy = '原因： ' . $order_data['cancel_explain'];
                }
                switch ($order_data['order_status_id']) {
                    case '-1':
                        $order_data['erxpress_data'] = array(
                            'erxpress_time' => $order_data['date_added'],
                            'erxpress_context' => '订单取消,' . $o_tetx . $yy,
                        );
                        break;
                    case '-2':
                        $order_data['erxpress_data'] = array(
                            'erxpress_time' => $order_data['date_added'],
                            'erxpress_context' => '您的订单已提交成功,等待您付款......',
                        );
                        break;
                    case '3':
                        $order_data['erxpress_data'] = array(
                            'erxpress_time' => $order_data['date_added'],
                            'erxpress_context' => '您的订单已支付成功,我们正在加紧备货',
                        );
                        break;
                }
            }


            //查询订单的收货地址
            $address_model = D('Address');
            $finds = 'address_id,name,telephone,area_name,address';
            $address_data = $address_model->getAddressInfo(array('address_id' => $order_data['address_id']), $finds);
            $order_data['address_data'] = $address_data;

            //查询商品信息
            $goods_model = D('Goods');
            //商品ig
            $goods_id = $order_data['goods_id'];
            $order_id = $order_data['order_id'];

            $finds = 'goods_id,name,image,before_discount';
            $g_where = array(
                'goods_id' => $goods_id,
            );

            //查询商品
            $goods_data = $goods_model->goodsInfo($g_where, $finds);
            $order_data['name'] = $goods_data['name'];
            $order_data['image'] = $goods_data['image'];
            //折前月供
            $order_data['before_yg'] = monthly_payment($order_data['price'], $goods_data['before_discount'], $order_data['datas']);

            //还款计划
            if ($order_data['payment_code'] == 'installments') {

                //根据下单时间算出还款时间
                //本金
                $bj = $order_data['price'] / $order_data['datas'];

                //时间
                $staging_time = $order_data['date_added'];
                $timestamp = strtotime($staging_time);
                $staging_time = date("Y-m-d", $timestamp);

                $staging_arr = array();
                for ($i = 1; $i <= $order_data['datas']; $i++) {
                    $staging_d = array(
                        'issue' => '第 ' . $i . ' 期',
                        'bj' => $bj,
                        'fwf' => $order_data['also_num'] - $bj,
                        'before_fwf' => monthly_interest($order_data['price'], $goods_data['before_discount'], $order_data['datas']), //折前服务费，就是折前每月应还利息

                    );

                    if ($order_data['order_status_id'] == '3' || $order_data['order_status_id'] == '5' || $order_data['order_status_id'] == '6') {
                        if ($i == '1') {
                            $staging_d['staging_time'] = $staging_time;
                            session('staging_time', $staging_time);
                        } else {
                            $staging_time = session('staging_time');
                            $staging_time = date("Y-m-d", strtotime("+1 months", strtotime($staging_time)));
                            $staging_d['staging_time'] = $staging_time;
                            session('staging_time', $staging_time);

                        }
                    }

                    $staging_arr[] = $staging_d;
                }
                $order_data['staging_data'] = $staging_arr;

            } else {
                $order_data['staging_data'] = array();
            }


            //查询商品的订单商品规格
            $orderOption_model = D('OrderOption');
            $orderOptio_w = array(
                'order_id' => $order_id,
            );

            $orderOption_data = $orderOption_model->orderOptioList($orderOptio_w);
            if (!empty($orderOption_data)) {
                $option_data = array();

                //查询订单商品
                foreach ($orderOption_data as $k => $v) {
                    $option_list = M()->query('select * from ' . C('DB_PREFIX') . 'order_goods where order_goods_id=' . $v['order_goods_id'] . ' and order_id=' . $v['order_id']);
                    $option_data[] = $option_list[0];
                }
            }

            //组装商品选项规格
            foreach ($option_data as $k => $v) {
                foreach ($orderOption_data as $kk => $vv) {
                    if ($v['order_goods_id'] == $vv['order_goods_id'] && $v['order_id'] == $vv['order_id']) {
                        $option_data[$k]['option_data'][] = $vv['name'] . ' : ' . $vv['value'];
                    }

                }

            }

            //组装商品选项规格
            foreach ($option_data as $kk => $vv) {
                if ($order_data['goods_id'] == $vv['goods_id']) {
                    $order_data['option_data'] = $vv['option_data'];
                }
            }


        } else {
            $order_data = array();
        }
        json_data(array('data_list' => $order_data));
    }


}